/*
    This file is part of tPortal.

    tPortal is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    tPortal is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with tPortal.  If not, see <http://www.gnu.org/licenses/>.

    The original code was written by Sebastien Bettinger <sebastien.bettinger@gmail.com>

 */

package net.tinyportal.tools;

 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
 
public class ZipUtils {
 
    public static final void main(String[] args) {
        /**
         * Initialize the default parameters
         */
        String zipFileName = "C:/myFolder/myZip.zip";
        String directoryToExtractTo = "C:/myFolder/unzipped/";
 
        /**
         * Check if the arguments are passed from console.
         * If so, we will discard the defalt parameters.
         */
 
        if (args.length != 2) {
            System.err.println("Usage: MyUnzipUtil zipfile unzipLocation");
            System.err.println("...Using The Hardcoded Zip Location");
        } else {
            zipFileName = args[0];
            directoryToExtractTo = args[1];
        }
 
        /**
         * Call the unzip method
         */
        unzipMyZip(zipFileName, directoryToExtractTo);
 
    }
 
    /**
     * This method
     * --Reads an input stream
     * --Writes the <span class="IL_AD" id="IL_AD11">value</span> to the output stream
     * --Uses 1KB buffer.
     */
    public static final void writeFile(InputStream in, OutputStream out)
            throws IOException {
        byte[] buffer = new byte[1024];
        int len;
 
        while ((len = in.read(buffer)) >= 0)
            out.write(buffer, 0, len);
 
        in.close();
        out.close();
    }
 
    public static void unzipMyZip(String zipFileName,
            String directoryToExtractTo) {
        Enumeration entriesEnum;
        ZipFile zipFile;
        try {
            zipFile = new ZipFile(zipFileName);
            entriesEnum = zipFile.entries();
 
            File directory= new File(directoryToExtractTo);
 
            /**
             * Check if the directory to extract to exists
             */
            if(!directory.exists())
            {
                /**
                 * If not, create a new one.
                 */
                new File(directoryToExtractTo).mkdir();
                System.err.println("...Directory Created -"+directoryToExtractTo);
            }
            while (entriesEnum.hasMoreElements()) {
                try {
                    ZipEntry entry = (ZipEntry) entriesEnum.nextElement();
 
                    if (entry.isDirectory()) {
                        /**
                         * Currently not unzipping the directory structure.
                         * All the files will be unzipped in a Directory
                         *
                         **/
                    } else {
 
                        System.err.println("Extracting file: "
                                + entry.getName());
                        /**
                         * The following logic will just extract the file name
                         * and discard the directory
                         */
                        int index = 0;
                        String name = entry.getName();
                        index = entry.getName().lastIndexOf("/");
                        if (index > 0 && index != name.length())
                            name = entry.getName().substring(index + 1);
 
                        System.out.println(name);
 
                        writeFile(zipFile.getInputStream(entry),
                                new BufferedOutputStream(new FileOutputStream(
                                        directoryToExtractTo + name)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
 
            zipFile.close();
        } catch (IOException ioe) {
            System.err.println("Some Exception Occurred:");
            ioe.printStackTrace();
            return;
        }
    }
    
    public static void unzip(String filename, String destinationname) {
    	   try {
      

    	             byte[] buf = new byte[1024];
    	             ZipInputStream zipinputstream = null;
    	             ZipEntry zipentry;
    	             zipinputstream = new ZipInputStream(new FileInputStream(filename));
    	            zipentry = zipinputstream.getNextEntry();
    	            File destinationFile = new File(destinationname);
    	            if (!destinationFile.exists()) {
    	            	destinationFile.mkdirs();
    	            }
    	 
    	           while (zipentry != null) {

    	                 // for each entry to be extracted
    	                 String entryName = zipentry.getName();
    	    
    	                 int n;
    	                FileOutputStream fileoutputstream;
    	                File newFile = new File(entryName);

    	              String directory = newFile.getParent();

    	              // to creating the parent directories
    	              if (directory == null) {
    	                   if (newFile.isDirectory()){
    	                         break;
    	                      }
    	             } else {
    	                 new File(destinationname+directory).mkdirs();
    	              }
    	    

    	            if(!zipentry.isDirectory()){
    	                       System.out.println("File to be extracted....."+ entryName);
    	                       fileoutputstream = new FileOutputStream(destinationname  + entryName);
    	                      while ((n = zipinputstream.read(buf, 0, 1024)) > -1){
    	                              fileoutputstream.write(buf, 0, n);
    	                       }
    	                      fileoutputstream.close();
    	            }
    	             
    	           zipinputstream.closeEntry();
    	           zipentry = zipinputstream.getNextEntry();
    	          }// while
    	  
    	     zipinputstream.close();
    	   } catch (Exception e) {
    	    e.printStackTrace();
    	   }
    	  }
}